<?php
/**
 * Library Of Shared Code (LOSC)
 *
 * LICENSE
 *
 * This source file is subject to the New BSD License that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @category   LOSC Framework
 * @package    Validate
 * @copyright  Copyright (c) 2008 Robin Skoglund (http://robinsk.net/)
 * @license    http://creativecommons.org/licenses/BSD/  New BSD License
 */

/**
 * Validator for checking that a Doctrine record exists
 *
 * @category   LOSC Framework
 * @package    Validate
 * @copyright  Copyright (c) 2008 Robin Skoglund (http://robinsk.net/)
 * @license    http://creativecommons.org/licenses/BSD/  New BSD License
 */
class Losc_Validate_RecordExists extends Zend_Validate_Abstract
{
    const NOT_EXIST = 'recordDoesNotExist';

    /**
     * Error messages
     * 
     * @var array
     */
    protected $_messageTemplates = array(
        self::NOT_EXIST => 'Record with id "%value%" does not exist.'
    );
    
    /**
     * Name of record to check for
     *
     * @var string
     */
    protected $_recordName;
    
    /**
     * Creates validator
     *
     * @param string $recordName  name of record to check for
     */
    public function __construct($recordName)
    {
        $this->_recordName = (string) $recordName;
    }
    
    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if a record with id $value exists. 
     * 
     * @param  string $value
     * @return boolean
     */
    public function isValid($value)
    {
        $this->_setValue($value);

        $r = Doctrine::getTable($this->_recordName)
             ->find($value, Doctrine::HYDRATE_ARRAY);

        if (!is_array($r) || empty($r)) {
            $this->_error();
            return false;
        }
        
        return true;
    }
}
